#!/usr/bin/env python3
# coding: utf-8
# from typing import Dict, Union
from datetime import datetime, timedelta
import freeswitch
import time
import random
import demjson


# 呼入处理入口
# from 集成商invite, 检测目标号码注册在哪台FS，在本台则直接桥接，转接到该台FS
#注： 未测试
localhost_ip = "172.16.8.87"
profile_internal_port = "5070"
# call_prix_dict = {
#     '1': '90000011',  # 广州
#     '2': '90000013',  # 东莞
#     '3': '90000012'  # 佛山
# }
record_save_base_paths = ["/cloudcall_file/rec_20050/freeswitchRecordFile/",
                          "/cloudcall_file/rec_20051/freeswitchRecordFile/"]


def handler(session, args):  # args is string
    session.setAutoHangup(False)
    uuid = session.getVariable("uuid")

    if args is None:
        freeswitch.console_log("info", "call %s has no target call number in args param\n" % uuid)
        session.hangup("UNALLOCATED_NUMBER")
        return

    freeswitch.console_log("info", "call %s args string is: %s \n" % (uuid, args))

    api = freeswitch.API()  ##freeswitch的API
    #1
    regStatus = api.executeString("sofia status profile internal reg " + args)
    freeswitch.consoleLog("ERR", "regStatus: %s \n" % regStatus)
    # freeswitch.console_log("info", regStatus)

    try:
        beginIndex = regStatus.find("User:")  ##截取字符串
        if beginIndex > -1:  ##假如不为None,就是已经注册在线
            ##获取注册
            beginIndex = regStatus.find(args + "@")
            endIndex = regStatus.find("Contact:")
            freeswitch.consoleLog("NOTICE", "endIndex: %s \n" % str(endIndex))
            regRealm = regStatus[beginIndex:endIndex]
            regRealm = regRealm.strip("\n")
            #1004@testfs.ihk.cn
            freeswitch.consoleLog("NOTICE", "reg user: " + args + ", realm : " + regRealm)
        else:
            freeswitch.consoleLog("ERR", "user " + args + "尚未注册")
            session.hangup("USER_NOT_REGISTERED")

        #'桥接本地服务user'
        if regRealm.find(localhost_ip) > -1:
            # call_str = "user/"+args
            # 转到inboundcall2.py的拨号计划，录音，录音地址等
            session.execute("transfer", "%s XML default" % args)
        else:
            #转接到另一台FS的internal profile,执行inboundcall2.py
            call_str = "sofia/internal/%s:%s;%s" % (regRealm, profile_internal_port, "transport=tcp")
            freeswitch.console_log("NOTICE", "bridge string is: %s \n" % call_str)
            # session.execute("bridge", "user/%s" % args)
            session.execute("bridge", call_str)
        #??有用？？
        session.hangup()
    except Exception as err:
        freeswitch.console_log("err", "call %s exception,msg: %s \n" % (uuid, str(err)))
        session.hangup("ORIGINATOR_CANCEL")


def hangup_hook(uuid):
    freeswitch.console_log("info", "myHangupHook, uuid: %s!!\n" % uuid)
    return "Result"
